<?php

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * Description of Auth
 *
 * @author sanka
 */
namespace Managers;

class Auth extends \Lib\Model\DoctrineManager {

    const NOT_FOUND             = 1;
    const WRONG_PASSWORD        = 2;
    const FAILURE               = 3;
    const IDENTITY_AMBIGUOUS    = 4;


    /**
     *
     * @var string
     */
    private $_identityCol;

    /**
     *
     * @var string
     */
    private $_credentialCol;
    /**
     *
     * @var string
     */
    private $_tableName;

    public function __construct($identityCol, $credentialCol, $tableName) {
        
        $this->_identityCol = $identityCol;
        $this->_credentialCol = $credentialCol;
        $this->_tableName = $tableName;
    }

    public function authenticate($email, $password) {
        
        if (!$this->_tableName) {
            throw new \Exception('Table name is empty', self::FAILURE);
        }
        try {
            
//            $users = $this->getEntityManager()->getRepository($this->_tableName)->findOneBy(array('email'=>$email));
            $sql = $this->getEntityManager()
                    ->createQueryBuilder()
                    ->select('u')
                    ->from($this->_tableName, 'u')
                    ->where('u.eMail = :email')
                    ->setParameter('email', $email)
                    ->setMaxResults('1')
                    ->getQuery();
            
            $users = $sql->getResult();
            
        } catch (\Exception $e) {
            throw new \Exception('Wrong identity or credential column', self::FAILURE);
        }
        if (count($users)) {

            if (count($users) > 1) {
                throw new \Exception('Identity ambiguous', self::IDENTITY_AMBIGUOUS);
            }

            foreach ($users as $user) {
                if ($user->getPassword() == $password) {
                    return $user;
                } else {
                    throw new \Exception('Wrong password', self::WRONG_PASSWORD);
                }
            }
        } else {
            throw new \Exception('Not found', self::NOT_FOUND);
        }
    }

}